<?php 
namespace app\api\controller;

use think\Exception;
use think\Controller;
use app\common\exception\BaseException;
use app\api\model\Type as TypeModel;

class Type extends Controller {
    public function getList() {
        $data = TypeModel::all();
        return json([
            "msg"=>"sucess",
            "code"=> 20000,
            "data"=>$data
        ],200);
    }

    public function addType() {
        // $data = new TypeModel();
        // $res = $data->save($this->request->param());
        if($this->request->param('id')) {
            $type = TypeModel::get($this->request->param('id'));
        }else {
            $type = new TypeModel();
        }

        $file = request()->file('img');
        // 移动到框架应用根目录/uploads/ 目录下
        $info = $file->move( './uploads');
      
        if($info){
            // 成功上传后 获取上传信息
            $type->img = $info->getSaveName();
            $type->name = $this->request->param('name');
            $data = $type->save();
            if($data) {
                return json([
                    "msg"=> "success",
                    "code"=>20000
                ],200);
            }
        }else{
            // 上传失败获取错误信息
            echo $file->getError();
        }



        if($res) {
            return json([
                "msg"=>"sucess",
                "code"=> 20000
            ],200);
        }else {
            return json([
                "msg"=>"faile",
                "code"=> 10000
            ],200);
        }

    }

    public function deleteType() {
        $data = TypeModel::get($this->request->param("id"));
        $res = $data->delete();
        if($res) {
            return json([
                "msg"=>"sucess",
                "code"=> 20000
            ],200);
        }else {
            return json([
                "msg"=>"删除失败",
                "code"=> 10000
            ],200);
        }
    }
}